<?php

namespace App\Repository\Models;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class UserCollection.
 *
 * @package namespace App\Repository\Models;
 */
class UserCollection extends Model implements Transformable
{
    use TransformableTrait;
    use SoftDeletes;
    protected $table = 'user_collection';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id','shop_id','product_id','sku_id','type','created_at','updated_at','deleted_at','is_invalid'];

    protected $appends  = ['business_product','hot_product'];

    /**
     *
     * @TODO 获取店铺的主营产品
     *
     * @var array
     */
    public function getBusinessProductAttribute(){
        $business_product = [];
        // 根据 shop_id 获取 company_id
        $shopInfo = Shop::query()->where('sp_id',$this->shop_id)->get()->toArray();
        if (isset($shopInfo[0])){
            $company_id = $shopInfo[0]['sp_cmp_id'];

            // 根据 company_id 获取 business_product
            $company = CompanyMaterial::query()->where('company_id',$company_id)->get()->toArray();
            if (isset($shopInfo[0])){
                $business_product = json_decode($company[0]['business_product'],1);
            }
        }

        return $business_product;
    }
    /**
     *
     * @TODO 获取店铺的热销商品
     *
     * @var array
     */
    public function getHotProductAttribute(){
        $products = [];
        // 根据 shop_id 获取 product succ_num 交易成功数最多的商品 降序排序
        $products    = Products::query()->where('shop_id',$this->shop_id)->where('is_for_sale',1)->where('product_type',1)->orderBy('succ_num', 'desc')->take(6)->get()->toArray();
        $hot_product = $products;
        return $hot_product;
    }
    public function shop()
    {
        return $this->hasOne(Shop::class, 'sp_id', 'shop_id');
    }
    public function sku()
    {
        return $this->hasOne(ProductSkus::class, 'id', 'sku_id');
    }
    public function product()
    {
        return $this->hasOne(Products::class, 'id', 'product_id');
    }
}
